package com.googlecode.lookie.maven;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.dependency.utils.DependencyStatusSets;
import org.apache.maven.plugin.dependency.utils.DependencyUtil;
import org.apache.maven.plugin.dependency.utils.filters.DestFileFilter;
import org.apache.maven.plugin.dependency.utils.resolvers.ArtifactsResolver;
import org.apache.maven.plugin.dependency.utils.resolvers.DefaultArtifactsResolver;
import org.apache.maven.plugin.dependency.utils.translators.ArtifactTranslator;
import org.apache.maven.plugin.dependency.utils.translators.ClassifierTypeTranslator;
import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.io.InputStreamFacade;

/**
 * @goal pde-target
 *
 * @requiresDependencyResolution test
 *
 * @phase process-sources
 */
public class PdeTargetMojo
    extends AbstractFromDependenciesMojo
{

    /**
     * Main entry into mojo. Gets the list of dependencies and iterates through calling copyArtifact.
     *
     * @throws MojoExecutionException with a message if an error occurs.
     * @see #getDependencies
     * @see #copyArtifact(Artifact, boolean)
     */
    public void execute()
        throws MojoExecutionException
    {
        DependencyStatusSets dss = getDependencySets( false );
        Set artifacts = dss.getResolvedDependencies();

        for ( Iterator i = artifacts.iterator(); i.hasNext(); )
        {
            copyArtifact( (Artifact) i.next(), false );
        }

        artifacts = dss.getSkippedDependencies();
        for ( Iterator i = artifacts.iterator(); i.hasNext(); )
        {
            Artifact artifact = (Artifact) i.next();
            getLog().info( artifact.getFile().getName() + " already exists in destination." );
        }

        File sourcePluginDirectory = new File( outputDirectory, "com.googlecode.lookie.target.sources-1.0.0" );

        File sourceDirectory = new File( sourcePluginDirectory, "src" );

        if ( !sourceDirectory.exists() )
        {
            sourceDirectory.mkdirs();
        }

        File metaInfDirectory = new File( sourcePluginDirectory, "META-INF" );

        if ( !metaInfDirectory.exists() )
        {
            metaInfDirectory.mkdirs();
        }

        Manifest manifest = new Manifest();
        manifest.getMainAttributes().putValue( "Manifest-Version", "1.0" );
        manifest.getMainAttributes().putValue( "Bundle-SymbolicName",
                                               "com.googlecode.lookie.target.sources;singleton:=true" );
        manifest.getMainAttributes().putValue( "Bundle-Version", "1.0.0" );
        manifest.getMainAttributes().putValue( "Bundle-ManifestVersion", "2" );

        try
        {
            manifest.write( new FileOutputStream( new File( metaInfDirectory, "MANIFEST.MF" ) ) );
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( "", e );
        }

        try
        {
            FileUtils.copyStreamToFile( new InputStreamFacade()
            {

                public InputStream getInputStream()
                    throws IOException
                {
                    return getClass().getResourceAsStream( "plugin.xml" );
                }

            }, new File( sourcePluginDirectory, "plugin.xml" ) );
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( "", e );
        }

        artifacts = dss.getResolvedDependencies();
        for ( Iterator i = artifacts.iterator(); i.hasNext(); )
        {
            Artifact artifact = (Artifact) i.next();
            contributeSource( sourceDirectory, artifact );
        }
    }

    protected void contributeSource( File sourcesDir, Artifact artifact )
        throws MojoExecutionException
    {
        Manifest manifest = null;
        try
        {
            manifest = readManifest( artifact );
        }
        catch ( IOException e )
        {
            getLog().warn( "error reading manifest for " + artifact.getArtifactId(), e );
        }

        if ( manifest != null )
        {
            String name = manifest.getMainAttributes().getValue( "Bundle-SymbolicName" );
            String version = manifest.getMainAttributes().getValue( "Bundle-Version" );

            sourcesDir = new File( sourcesDir, name + "_" + version );

            Set artifacts = new HashSet();
            artifacts.add( artifact );

            ArtifactTranslator translator = new ClassifierTypeTranslator( this.classifier, this.type, this.factory );
            artifacts = translator.translate( artifacts, getLog() );

            // resolve the rest of the artifacts
            ArtifactsResolver artifactsResolver = new DefaultArtifactsResolver( this.resolver, this.local,
                                                                                this.remoteRepos, false );
            artifacts = artifactsResolver.resolve( artifacts, getLog() );

            Artifact source = null;
            Iterator it = artifacts.iterator();
            if ( it.hasNext() )
            {
                if ( !sourcesDir.exists() )
                {
                    sourcesDir.mkdirs();
                }

                source = (Artifact) it.next();
                File destFile = new File( sourcesDir, "src.zip" );
                copyArtifact( source, destFile );
            }
            else
            {
                getLog().info( "no source attachement found for " + artifact.getArtifactId() );
            }
        }
    }

    protected Manifest readManifest( Artifact artifact )
        throws ZipException, IOException
    {
        ZipFile zip = new ZipFile( artifact.getFile() );
        ZipEntry entry = zip.getEntry( "META-INF/MANIFEST.MF" );
        InputStream is = zip.getInputStream( entry );
        Manifest manifest = new Manifest();
        manifest.read( is );

        return manifest;
    }

    /**
     * Copies the Artifact after building the destination file name if overridden. This method also checks if the
     * classifier is set and adds it to the destination file name if needed.
     *
     * @param artifact representing the object to be copied.
     * @param removeVersion specifies if the version should be removed from the file name when copying.
     * @throws MojoExecutionException with a message if an error occurs.
     * @see DependencyUtil#copyFile(File, File, Log)
     * @see DependencyUtil#getFormattedFileName(Artifact, boolean)
     */
    protected void copyArtifact( Artifact artifact, boolean removeVersion )
        throws MojoExecutionException
    {

        String destFileName = DependencyUtil.getFormattedFileName( artifact, removeVersion );

        copyArtifact( artifact, destFileName );
    }

    protected void copyArtifact( Artifact artifact, String destFileName )
        throws MojoExecutionException
    {
        File destDir;
        destDir = DependencyUtil.getFormattedOutputDirectory( false, false, false, false, outputDirectory, artifact );
        File destFile = new File( destDir, destFileName );

        copyArtifact( artifact, destFile );
    }

    protected void copyArtifact( Artifact artifact, File destFile )
        throws MojoExecutionException
    {
        copyFile( artifact.getFile(), destFile );
    }

    protected Artifact getResolvedPomArtifact( Artifact artifact )
    {
        Artifact pomArtifact = this.factory.createArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact
            .getVersion(), "", "pom" );
        // Resolve the pom artifact using repos
        try
        {
            this.resolver.resolve( pomArtifact, this.remoteRepos, this.local );
        }
        catch ( Exception e )
        {
            getLog().info( e.getMessage() );
        }
        return pomArtifact;
    }

    protected ArtifactsFilter getMarkedArtifactFilter()
    {
        return new DestFileFilter( this.overWriteReleases, this.overWriteSnapshots, this.overWriteIfNewer, false,
                                   false, false, false, this.outputDirectory );
    }

}
